package com.tansun.tandata.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.tansun.tandata.service.MenuService;
import com.tansun.tandata.utils.Constants;
import com.tansun.tandata.utils.LocaleMessage;
import com.tansun.tandata.utils.ParentController;
import com.tansun.tandata.utils.ResponseBase;
import com.tansun.tandata.vo.req.MenuVO;
import com.tansun.tandata.vo.req.TreeVo;
import com.tansun.tandata.vo.res.MenuNewVO;
import com.tansun.tandata.vo.res.MenuWithParentVO;
import com.tansun.tandata.vo.res.RoleInfoByRoleCodesVO;
import com.tansun.tjmas.cloud.base.redis.common.RedisConstant;
import com.tansun.tjmas.cloud.base.redis.utils.RedisUtils;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @Description 菜单信息控制器
 * @CreateDate 20200429
 * @author shenxiaodong
 * @Version v1.0
 *
 */
@RestController
@RequestMapping(value = "/sys/menu")
public class MenuController extends ParentController{
	@Autowired
	private MenuService menuService;

	@Autowired(required = false)
	private RedisUtils redisUtils;

	@Autowired
	private LocaleMessage localeMessage;

	@ApiOperation(value="根据角色id获取角色菜单树", notes="根据角色id获取角色菜单树")
	@ApiImplicitParam(name = "roleCode", value = "角色id", required = true, dataType = "String")
	@RequestMapping(value = "/roleMenu", method = RequestMethod.GET)
	public ResponseBase<List<String>> getMenuTreeByRoleCode(@RequestParam("roleCode") String roleCode) {
		List<String> menuIds = menuService.selectMenuByRoleCode(roleCode);
		return setResultSuccess(menuIds);
	}

	@ApiOperation(value="获取菜单树", notes="获取菜单树")
	@RequestMapping(value = "menuList", method = RequestMethod.GET)
	public ResponseBase<List<TreeVo>> selectAllMenu() {
		List<TreeVo> treeVos = menuService.selectAllMenu();
		return setResultSuccess(treeVos);
	}

	@ApiOperation(value="删除菜单基本信息", notes="删除菜单基本信息")
	@ApiImplicitParam(name = "id", value = "菜单id", required = true, dataType = "String")
	@RequestMapping(value="deleteMenu", method=RequestMethod.GET)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase deleteMenu(@RequestParam("id") String id){
		try {
			menuService.deleteMenuById(id);
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
		}
		return setResultSuccess(localeMessage.getMessage("sys.user.deleteSuccess"));
	}

	@ApiOperation(value="修改菜单信息", notes="修改菜单信息")
	@RequestMapping(value="updateMenu", method=RequestMethod.POST)
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public ResponseBase updateUser(@Valid @RequestBody MenuVO menuVO, BindingResult bindingResult){
		// 验证实体输入参数
		ResponseBase validResult = validateField(bindingResult);
		if (validResult != null) {
			return validResult;
		}
		//存在性验证，姓名验证
		int count = menuService.getMenuByChnNameOrEngName(menuVO.getFnChnNm(), menuVO.getFnEngNm(), menuVO.getId());
		if (count > Constants.CHAR_INT_ZERO) {
			return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.menu.name.isExist"), null);
		}
		try {
			menuService.updateMenu(menuVO);
			return setResultSuccess(menuVO);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null); //系统错误
		}
	}

	@ApiOperation(value="新增菜单", notes="新增菜单")
	@RequestMapping(value = "/saveMenu", method = RequestMethod.POST)
	public ResponseBase saveMenu(@Valid @RequestBody MenuVO menuVO, BindingResult bindingResult) {
		// 验证实体输入参数
		ResponseBase validResult = validateField(bindingResult);
		if (validResult != null) {
			return validResult;
		}
		//存在性验证，姓名验证
		int count = menuService.getMenuByChnNameOrEngName(menuVO.getFnChnNm(), menuVO.getFnEngNm(), menuVO.getId());
		if (count > Constants.CHAR_INT_ZERO) {
			return setResult(Constants.HTTP_RES_CODE_402, localeMessage.getMessage("sys.common.menu.name.isExist"), null);
		}
		try {
			menuService.saveMenu(menuVO);
			return setResultSuccess(menuVO);
		} catch (RuntimeException e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500, localeMessage.getMessage("sys.common.error"), null);
		}
	}

	@ApiOperation(value="根据菜单id获取带父菜单信息", notes="根据菜单id获取带父菜单信息")
	@ApiImplicitParam(name = "id", value = "菜单id", required = true, dataType = "String")
	@RequestMapping(value = "/selectMenuInfoById", method = RequestMethod.GET)
	public ResponseBase selectMenuInfoById(String id) {
		MenuWithParentVO menuWithParentVO = menuService.selectMenuWithParentInfoById(id);
		return setResultSuccess(menuWithParentVO);
	}

	@ApiOperation(value="查询所有角色编号和对应Api路径", notes="查询所有角色编号查询Api路径")
	@RequestMapping(value="/getRoleAndApis", method=RequestMethod.GET)
	public ResponseBase<List<RoleInfoByRoleCodesVO>> getRoleAndApis(){
		try {
			List<RoleInfoByRoleCodesVO> roleInfoByRoleCodesVOList = menuService.selectMenuApiByRoleCode();
			return setResultSuccess(JSON.toJSONString(roleInfoByRoleCodesVOList));
		} catch (Exception e) {
			e.printStackTrace();
			//系统错误
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null);
		}
	}

	@ApiOperation(value="根据缓存的角色编号查询菜单信息", notes="根据缓存的角色编号查询菜单信息")
	@RequestMapping(value="/getMenuInfosByRoleCodes", method=RequestMethod.GET)
	public ResponseBase<List<MenuNewVO>> getMenuInfosByRoleCodes(HttpServletRequest request){
		//1、获取用户roleCodes
		String redisId = request.getHeader(RedisConstant.REDIS_ID);
		HashMap<String, Object> roleCodeMap = (HashMap<String, Object>) redisUtils.get(redisId);
		String roleCodes = roleCodeMap.get("role").toString();
		try {
			List<MenuNewVO> menuList = menuService.getMenuInfosByRoleCodes(roleCodes);
			if(menuList==null||menuList.size()==0){
				menuList = new ArrayList<>();
			}
			return setResultSuccess(menuList);
		} catch (Exception e) {
			e.printStackTrace();
			return setResult(Constants.HTTP_RES_CODE_500,localeMessage.getMessage("sys.common.error"),null); //系统错误
		}
	}
}
